package main

import (
	"bufio"
	"fmt"
	c "itchat4go/controllers"
	e "itchat4go/enum"
	m "itchat4go/model"
	s "itchat4go/service"
	"logs"
	"os"
	"os/exec"
	"regexp"
	"strings"
	"time"
)

var (
	uuid       string
	err        error
)

func main() {

	logs.SetLogFuncCall(true)
	logs.Async(100)
	logs.SetLevel(logs.LevelDebug)
	os.Mkdir("logs", os.ModeDir)
	logs.SetLogger(logs.AdapterFile, `{"filename":"logs/project.log","maxlines":0,"daily":true,"maxdays":30}`)
	logs.SetLogger(logs.AdapterConsole, `{"color":true,"level":7}`)

	/* 从微信服务器获取UUID */
	uuid, err = s.GetUUIDFromWX()
	if err != nil {
		panicErr(err)
	}

	/* 根据UUID获取二维码 */
	err = s.DownloadImagIntoDir(e.QRCODE_URL+uuid, "./qrcode")
	panicErr(err)
	cmd := exec.Command(`cmd`, `/c start ./qrcode/qrcode.jpg`)
	err = cmd.Run()
	panicErr(err)

	go send_input()
	go send_input2()

	/* 轮询服务器判断二维码是否扫过暨是否登陆了 */
	c.Login(uuid)

	fmt.Println("开始获取联系人信息...")
	con, err2 := s.GetAllContact()
	if err2 != nil {
		panicErr(err2)
	}
	m.ContactMap = &con

	fmt.Printf("成功获取 %d个 联系人信息\n", len(*m.ContactMap))

	fmt.Println("开始监听消息响应...")
	var retcode, selector int64

	for {
		retcode, selector, err = s.SyncCheck(m.LoginM)
		if err != nil {
			logs.Error(retcode, selector, err)
			time.Sleep(time.Second * 65)
			continue
		}

		c.Handler_text(retcode, selector)
	}
}


var regAt = regexp.MustCompile(`^.*@.*郭宇.*$`)
var regGroup = regexp.MustCompile(`^@@.+`)
var regAd = regexp.MustCompile(`(朋友圈|点赞)+`)
var regName = regexp.MustCompile(`^*(晴|郭宇)+`)

func panicErr(err error) {
	if err != nil {
		panic(err)
	}
}

func printErr(err error) {
	if err != nil {
		fmt.Println(err)
	}
}

type msg struct {
	Name    string
	Content string
}

var msgList = make(chan msg, 100)

func send_input2() {
	for true {
		time.Sleep(time.Millisecond * 500)
		select {
		case msg := <-msgList:
			Name := msg.Name
			Content := msg.Content
			for k, v := range *m.ContactMap {
				RemarkName := v.RemarkName
				NickName := v.NickName
				if RemarkName != "" {
					if strings.Contains(Name, RemarkName) {
						c.SendMsg(k, Content)
					}
				} else if NickName != "" && strings.Contains(Name, NickName) {
					c.SendMsg(k, Content)
				}
			}
		}

	}
}

func send_input() {
	running := true
	reader := bufio.NewReader(os.Stdin)
	for running {
		data, _, _ := reader.ReadLine()
		command := string(data)
		split := strings.Split(command, ",")
		if split == nil || len(split) < 2 {
			continue
		}
		if command == "stop" {
			running = false
		}
		m := msg{
			Name:    split[0],
			Content: split[1],
		}
		msgList <- m
	}
}
